package com.wushi.lenovo.asia5b.app_push;

import android.app.Application;
import android.content.Context;
import android.os.Build;

import com.mvp.helper.AbsCrashHelper;
import com.mvp.utils.JsonUtil;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.wushi.lenovo.asia5b.app_model.other.PushBean;
import com.wushi.lenovo.asia5b.app_model.other.UmengModel;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;

import static java.lang.String.format;
import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2019/4/4.
 * 获取设备id
 * device token什么情况下会变化？
 * 一种是设备卸载过，又重新安装，token可能会变化； 另一种是设备没有SD卡，设备id变化导致的device token变化。
 * 如果推送报appid错误很可能是由于友盟那里建立了两个项目用了同一个包名,删除掉一个项目即可
 * Avz1WgWLFXTw3-GKm9EeP7FsMz-FvNGccBwm8TMVmnOO
 */
public class UMengPushHelper extends PushHelper {



    public static void registUmengPush(Application application) {
        /**
         * 设置日志加密
         * 参数：boolean 默认为false（不加密）
         */
        UMConfigure.setEncryptEnabled(false);

        PushAgent mPushAgent = PushAgent.getInstance(application);
//        mPushAgent.setNotificaitonOnForeground(false);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                d("友盟推送--->>>>>>>>---友盟注册成功deviceToken:" + deviceToken);
                PushHelper.setRegistrationIdAndType(deviceToken, "1");
            }

            @Override
            public void onFailure(String s, String s1) {
                d("友盟推送--->>>>>>>>---友盟注册失败:" + format("s:%s,s1:%s1", s, s1));
                app_register_error_msg = Build.MODEL + ";" + s + ";" + s1;
            }
        });
        mPushAgent.setDisplayNotificationNumber(2);

        UmengNotificationClickHandler notificationClickHandler = new WUmengNotificationClickHandler() {

            @Override
            public void launchApp(Context context, UMessage msg) {
                super.launchApp(context, msg);
                parseUmengData(msg);
            }

            /**
             * 自定义行为
             * @param context
             * @param msg
             */
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
                super.dealWithCustomAction(context, msg);
                parseUmengData(msg);
            }
        };
        mPushAgent.setNotificationClickHandler(notificationClickHandler);
    }

    private static void parseUmengData(UMessage msg) {
        if (msg != null) {
            Observable.just(msg)
                    .map(new Function<UMessage, PushBean>() {
                        @Override
                        public PushBean apply(UMessage uMessage) throws Exception {
                            UmengModel umengModel = JsonUtil.INSTANCE.jsonToAny(msg.getRaw().toString(), UmengModel.class);
                            return umengModel.getExtra();
                        }
                    })
                    .subscribeOn(AndroidSchedulers.mainThread())
                    .subscribe(extra -> {
                                channelData(extra);
                            },
                            throwable -> {
                                AbsCrashHelper.postCatchedException(throwable);
                            });
        }
    }



}
